package jmine.tec.test.jndi;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

/**
 * Classe que exporta um objeto em um contexto jndi
 * 
 * @author takeshi
 */
public class JNDIExporter implements InitializingBean, DisposableBean {

    private Object objectToExpose;

    private String jndiName;

    private Context jndiContext;

    /**
     * {@inheritDoc}
     */
    public void afterPropertiesSet() throws Exception {
        this.getJndiContext().bind(this.jndiName, this.objectToExpose);
    }

    /**
     * @return {@link InitialContext}
     * @throws NamingException e
     */
    public Context getJndiContext() throws NamingException {
        if (this.jndiContext == null) {
            this.jndiContext = new InitialContext();
        }
        return this.jndiContext;
    }

    /**
     * @param objectToExpose the objectToExpose to set
     */
    public void setObjectToExpose(Object objectToExpose) {
        this.objectToExpose = objectToExpose;
    }

    /**
     * @param jndiName the jndiName to set
     */
    public void setJndiName(String jndiName) {
        this.jndiName = jndiName;
    }

    /**
     * @param initialContext the initialContext to set
     */
    public void setJndiContext(Context initialContext) {
        this.jndiContext = initialContext;
    }

    /**
     * {@inheritDoc}
     */
    public void destroy() throws Exception {
        if(this.jndiContext != null) {
            this.jndiContext.unbind(this.jndiName);
        }
    }

}
